package com.mazaiting.cryption.sm.sm3;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import java.nio.charset.StandardCharsets;
import java.security.Security;

/**
 * SM3 工具类
 *
 * @author mazaiting
 * @create_time 2022/4/4 09:26
 */
public class SM3Util {

    static {
        // 添加加密库
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 签名
     *
     * @param srcData 待签名数据
     * @return 签名数据
     */
    public static String sign(String srcData) {
        try {
            System.out.println("签名内容: " + srcData);
            byte[] tmp = hash(srcData);
            String hashStr = ByteUtils.toHexString(tmp);
            System.out.println("签名后内容: " + hashStr);
            return hashStr;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取hash值
     *
     * @param srcData 源数据
     * @return hash数组
     */
    private static byte[] hash(String srcData) {
        byte[] bytes = srcData.getBytes(StandardCharsets.UTF_8);
        SM3Digest digest = new SM3Digest();
        digest.update(bytes, 0, bytes.length);
        byte[] hash = new byte[digest.getDigestSize()];
        digest.doFinal(hash, 0);
        return hash;
    }

}
